import { Injectable } from '@angular/core';
import { HttpEvent,HttpInterceptor,HttpHandler,HttpRequest,HttpResponse} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError } from 'rxjs/operators';
import { mergeMap } from 'rxjs/operators';
import { StorageProvider } from '../providers/storage/storage';
import { NotificationProvider } from '../providers/notification/notification';
@Injectable()
export class InterceptorService implements HttpInterceptor{
    
    constructor(
      private storage: StorageProvider,
      private notification: NotificationProvider
      ){}

  intercept(req:HttpRequest<any>,next:HttpHandler):Observable<HttpEvent<any>>{
    let userInfo = this.storage.getObject('userinfo');
    let authReq = req;
    if(userInfo){
      const token = userInfo.user_token || '';
      if (!!token) { 
          authReq = req.clone({
              setHeaders: {
                  'usertoken': token
              }
          });
      }
    }
 
    return next.handle(authReq).pipe(mergeMap((event: any) => {
        if (event instanceof HttpResponse && event.status != 200) {
          return ErrorObservable.create(event);
        }
        return Observable.create(observer => observer.next(event)); //请求成功返回响应
      }),
      catchError((res: HttpResponse<any>) => {   //请求失败处理
        switch (res.status) {
          case 401:
            break;
          case 200:
            console.log('业务错误');
            break;
          case 404:
            this.notification.showToast("服务器错误");
            break;
          case 403:
            console.log('业务错误');
            break;
        }
        this.notification.hideLoading();
        return ErrorObservable.create(event);
      }));
  }
}
